import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  HttpException as NestHttpException,
} from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

interface Response<T> {
  data: T;
  code: number;
  message: string;
  success: boolean;
}

@Injectable()
export class HttpExceptionInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      // 处理正常响应
      map(data => ({
        data,
        code: 200,
        message: '请求成功',
        success: true,
      })),
      // 处理异常
      catchError(error => {
        if (error instanceof NestHttpException) {
          const response = error.getResponse();
          // 处理自定义异常
          if (typeof response === 'object') {
            return throwError(() => ({
              code: response['code'] || error.getStatus(),
              message: response['message'] || '请求失败',
              data: response['data'] || null,
              success: response['success'] || false,
            }));
          }
        }
        // 处理其他未知异常
        return throwError(() => ({
          code: 500,
          message: '服务器内部错误',
          data: null,
          success: false,
        }));
      }),
    );
  }
} 